#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    :
# @Author  : GY
# @File    : read_host.py
#采集主机行为数据，并按照规定数据格式，生成JSON文件

import os
import time
import json


def read_Host():
    f = open("log//conn.log", "r")
    foreignHost = []
    hostTime = []
    userName = []
    localHost = []
    while True:
        line = f.readline()
        if line:
            line = line.strip('\n')
            line = line.split(",")
            foreignHost.append(line[3])
            hostTime.append(line[0])
            userName.append(line[1])
            localHost.append(line[2])
            # print(line[0])  #时间
            # print(line[1])  #用户名
            # print(line[2])  #本地主机名
            # print(line[3])  #远程用户
            # print("************")
        else:
            break
    return foreignHost, hostTime, userName, localHost


def read_VM():
    f = open("log//vm.log", "r")
    vmName = []
    vmTime = []
    port = []
    while True:
        line = f.readline()
        if line:
            line = line.strip('\n')
            line = line.split(",")
            vmName.append(line[0])
            vmTime.append(line[2])
            port.append(line[1])
        else:
            break
    return vmName, vmTime, port


def Write_Host_json(foreignHost, hostTime, userName, localHost, vmName, vmTime, port):
    data_dir = {
        "msg": "report",
        "layer": "host",
        "layer_info": {
            "localhost": [

            ],
            "vm": [

            ],
        }
    }

    for i in range(len(foreignHost)):
        name = {}
        name["foreignHost"] = foreignHost[i]
        name["userName"] = userName[i]
        name["localHost"] = localHost[i]
        name["hostTime"] = hostTime[i]
        data_dir["layer_info"]["localhost"].append(name)

    for i in range(len(vmName)):
        name = {}
        name["vmName"] = vmName[i]
        name["port"] = port[i]
        name["vmTime"] = vmTime[i]
        data_dir["layer_info"]["vm"].append(name)

    # path = os.getcwd() + '/JsonFileReport/'  # 获取当前工程下的JsonFile目录
    # with open(path + 'report_host.json', "w") as f:
    with open('report_host.json', "w") as f:
        json.dump(data_dir, f)
        print("*****主机行为信息写入json成功*****")
    f.close()
    return 0


def ReadHost_WriteJson():
    foreignHost, hostTime, userName, localHost = read_Host()
    vmName, vmTime, port = read_VM()
    Write_Host_json(foreignHost, hostTime, userName, localHost, vmName, vmTime, port)


if __name__ == '__main__':
    ReadHost_WriteJson()
